package com.siwei.mes.service.experiment.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.siwei.mes.common.query.PageQuery;
import com.siwei.mes.common.util.DateHelper;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.entity.experiment.*;
import com.siwei.mes.mapper.experiment.*;
import com.siwei.mes.service.experiment.TestBlockService;
import com.siwei.mes.service.system.AuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

/**
 * @Description: 压试块
 * @Version: 1.0
 * @author: chenmaolin
 * @date: 2024/1/1 01:04
 */
@Service
public class TestBlockServiceImpl implements TestBlockService {
    @Resource
    private TestBlockMapper testBlockMapper;
    @Resource
    private ExperimentSampleSmokeMapper experimentSampleSmokeMapper;
    @Resource
    private ExperimentImageMapper experimentImageMapper;
    @Resource
    private ExperimentSampleSmokeLogMapper experimentSampleSmokeLogMapper;
    @Resource
    private AuthService authService;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;

    @Override
    public PageInfo<TestBlockInfo> getPage(PageQuery<TestBlockInfo, TestBlockInfo> query) {
        TestBlockInfo params = query.getParams();
        PageInfo<TestBlockInfo> pageInfo = PageHelper.startPage(query.getPageNum(), query.getPageSize())
                .doSelectPageInfo(() -> testBlockMapper.getList(params));
        for (TestBlockInfo testBlockInfo : pageInfo.getList()) {
            if (testBlockInfo.getIsToday() != null && testBlockInfo.getIsToday() == 1) {
                continue;
            }
            /**判断还有多久的时间*/
            Date endDate = testBlockInfo.getLastTime();
            Date nowDate = new Date();
            Map<String, Object> map = DateHelper.timeDifference(endDate, nowDate);
            if (map.isEmpty()) {
                continue;
            }
            StringBuilder stringBuilder = new StringBuilder();
            long day = (long) map.get("day");
            long hour = (long) map.get("hour");
            if (day > 0) {
                stringBuilder.append(day).append("天");
            }
            if (hour > 0) {
                stringBuilder.append(hour).append("小时");
            }
            testBlockInfo.setStatusRemark(stringBuilder.toString());
        }
        return pageInfo;
    }

    @Override
    public TestBlockInfo loadById(Long id) {
        TestBlockInfo testBlockInfo = testBlockMapper.loadById(id);
        if (testBlockInfo != null) {
            if (testBlockInfo.getIsToday() != null && testBlockInfo.getIsToday() == 1) {
                return testBlockInfo;
            }
            /**判断还有多久的时间*/
            Date endDate = testBlockInfo.getLastTime();
            Date nowDate = new Date();
            Map<String, Object> map = DateHelper.timeDifference(endDate, nowDate);
            if (map.isEmpty()) {
                return testBlockInfo;
            }
            StringBuilder stringBuilder = new StringBuilder();
            long day = (long) map.get("day");
            long hour = (long) map.get("hour");
            if (day > 0) {
                stringBuilder.append(day).append("天");
            }
            if (hour > 0) {
                stringBuilder.append(hour).append("小时");
            }
            testBlockInfo.setStatusRemark(stringBuilder.toString());
        }
        return testBlockInfo;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void finish(Long id) {
        ExperimentSampleSmoke sampleSmoke = experimentSampleSmokeMapper.loadById(id);
        assertTrue(sampleSmoke == null, "抽样信息不存在");
        testBlockMapper.updateIsFinish(id);

        sampleSmoke.setDisposerPersonId(authService.getLoginUserId());
        sampleSmoke.setDisposerPersonName(authService.getLoginUserName());
        sampleSmoke.init(false);
        experimentSampleSmokeMapper.updateByPrimaryKeySelective(sampleSmoke);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TestBlockInfo entity) {
        ExperimentSampleSmoke sampleSmoke = experimentSampleSmokeMapper.loadById(entity.getId());
        assertTrue(sampleSmoke == null, "抽样信息不存在");
        sampleSmoke.setSampleTestProjectJson(entity.getSampleTestProjectJson());
        sampleSmoke.setSampleImg(entity.getTestBlockInfoImg());
        sampleSmoke.init(false);
        experimentSampleSmokeMapper.updateByPrimaryKeySelective(sampleSmoke);

        /**如果有图片 添加图片记录*/
        String testBlockInfoImg = entity.getTestBlockInfoImg();
        if (StringUtils.isNotBlank(testBlockInfoImg)) {
            /**先删除之前所有抽样记录id的图片 只保存最新的*/
            experimentImageMapper.deleteBySmokeId(entity.getId());
            ExperimentImage image = new ExperimentImage();
            image.setId(null);
            image.setExperimentId(entity.getExperimentId());
            image.setSmokeId(entity.getId());
            image.setExperimentImg(entity.getTestBlockInfoImg());
            image.init();
            experimentImageMapper.insertSelective(image);

            Set<String> imgSet = new HashSet<>(Arrays.asList(testBlockInfoImg.split(",")));
            /**这里要做一下处理  把对应试验台账的抽样记录修改*/
            List<ExperimentDetail> experimentDetailList = experimentDetailMapper.selectByExperimentId(entity.getExperimentId(), entity.getTestProjectCode());
            for (ExperimentDetail detail : experimentDetailList) {
                if (StringUtils.isBlank(detail.getObjImg())) {
                    continue;
                }
                List<String> imgList = Arrays.asList(detail.getObjImg().split(","));
                imgSet.addAll(imgList);

                String objImg = String.join(",", imgSet);
                detail.setObjImg(objImg);
                detail.init(false);
                experimentDetailMapper.updateByPrimaryKeySelective(detail);
            }
        }

        /**添加操作日志*/
        ExperimentSampleSmokeLog smokeLog = new ExperimentSampleSmokeLog();
        smokeLog.setUserId(authService.getLoginUserId());
        smokeLog.setUserName(authService.getLoginUserName());
        smokeLog.setOperTime(new Date());
        smokeLog.setExperimentId(entity.getExperimentId());
        smokeLog.setSmokeId(entity.getId());
        smokeLog.setOperJson(JsonUtils.beanToObject(sampleSmoke));
        smokeLog.setSampleTestProjectCode(entity.getSampleTestProjectCode());
        smokeLog.setSampleTestProjectName(entity.getSampleTestProjectName());
        smokeLog.setSampleTestProjectJson(entity.getSampleTestProjectJson());
        experimentSampleSmokeLogMapper.insertSelective(smokeLog);
    }
}
